/**
 * JAVACC DEMO 1.0
 */
package com.apache.audit.server;

import com.apache.api.vo.ParamsVo;
import com.apache.audit.entity.LogModel;
import com.apache.audit.entity.LogOperation;
import com.apache.cache.util.Validator;
import com.apache.client.StringUtil;
import com.apache.method.SystemRunnable;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * description:  日志添加线程
 *
 * @author Hou Dayu 创建时间：2016-8-8
 */
public class LoggerServerRunnable extends SystemRunnable {

    private Logger log = Logger.getLogger(LoggerServerRunnable.class);

    private LoggerSaveHelper helper;

    private Object obj;

    private Map<String, String> logMap;

    public LoggerServerRunnable(Object obj, Map<String, String> logMap) {
        this.obj = obj;
        this.logMap = logMap;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see java.lang.Runnable#run()
     */
    public void run() {
        try {
            ParamsVo<LogOperation> param = new ParamsVo<LogOperation>();
            String mark = "false";
            LogOperation operation = new LogOperation();
            if ("save".equals(logMap.get("logType"))) {
                operation.setLogType("添加");
                if (Validator.isNotNull(logMap.get("returnValue"))) {
                    mark = "true";
                }
            } else if ("edit".equals(logMap.get("logType"))) {
                operation.setLogType("更新");
                if (Validator.isNotNull(logMap.get("returnValue"))) {
                    mark = logMap.get("returnValue");
                }
            } else if ("del".equals(logMap.get("logType"))) {
                operation.setLogType("删除");
                if (Validator.isNotNull(logMap.get("returnValue"))) {
                    mark = logMap.get("returnValue");
                }
            }
            if ("false".equals(mark))
                return;
            String infoName = logMap.get("logClassName").trim();
            LogModel model = getLoggerSaveHelper().getLogModel(infoName);
            if (Validator.isEmpty(model)) {
                return;
            }
            operation.setModelId(model.getModelId());
            operation.setLogIp(logMap.get("logIp"));
            operation.setCreatedTime(System.currentTimeMillis());
            operation.setCreateUser(logMap.get("userEname"));
            operation = getLoggerSaveHelper().getUserByEname(operation);
            if (!Validator.isEmpty(obj)) {
                Map beanInfo = StringUtil.convertBean(obj);
                getLoggerSaveHelper().logSave(operation, beanInfo);
            } else {
                getLoggerSaveHelper().logDeleteInfo(logMap.get("infoId"), operation);
            }
        } catch (Throwable e) {
            log.error(e);
        }
    }

    private LoggerSaveHelper getLoggerSaveHelper() {
        if (null == helper) {
            helper = LoggerSaveHelper.newIntance();
        }
        return helper;
    }

}
